from django.db.models import Q
from rest_framework import serializers
from .models import Goods, GoodsCategory, GoodsImage, Banner, \
    GoodsCategoryBrand, IndexAd


class BannerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Banner
        fields = '__all__'


class GoodsCategorySerializer3(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = '__all__'


class GoodsCategorySerializer2(serializers.ModelSerializer):
    sub_cat = GoodsCategorySerializer3(many=True)
    class Meta:
        model = GoodsCategory
        fields = '__all__'

class GoodsCategorySerializer(serializers.ModelSerializer):
    sub_cat = serializers.SerializerMethodField()

    class Meta:
        model = GoodsCategory
        fields = '__all__'

    def get_sub_cat(self, obj):
        sub_categories = obj.sub_cat.all()
        serializer = GoodsCategorySerializer(sub_categories, many=True)
        return serializer.data

# class GoodsCategorySerializer(serializers.ModelSerializer):
#     # sub_cat = GoodsCategorySerializer2(many=True)
#     class Meta:
#         model = GoodsCategory
#         fields = '__all__'

class GoodsImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsImage
        fields = ('image',)


class GoodsSerializer(serializers.ModelSerializer):
    category = GoodsCategorySerializer()
    images = GoodsImageSerializer(many=True)

    class Meta:
        model = Goods
        fields = '__all__'

class BrandSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategoryBrand
        fields = '__all__'


class IndexCategorySerializer(serializers.ModelSerializer):
    brands = BrandSerializer(many=True)
    goods = serializers.SerializerMethodField()
    sub_cat = GoodsCategorySerializer2(many=True)
    ad_goods = serializers.SerializerMethodField()

    def get_ad_goods(self, obj):
        goods_json = {}
        ad_goods = IndexAd.objects.filter(category=obj.id)
        if ad_goods:
            # 添加context 参数，让goods 序列化器可以获取request，就会在序列话调用序列化的时候在图片前面添加域名了
            goods_json = GoodsSerializer(ad_goods[0].goods, many=False,
                                         context={'request': self.context['request']}).data
        return goods_json

    def get_goods(self, obj):
        all_goods = Goods.objects.filter(Q(category_id=obj.id) |
                                 Q(category__parent_category_id=obj.id) |
                                 Q(category__parent_category__parent_category_id=obj.id))
        # 添加context 参数，让goods 序列化器可以获取request，就会在序列话调用序列化的时候在图片前面添加域名了
        goods_serializer = GoodsSerializer(all_goods, many=True,
                                           context={'request': self.context['request']})
        return goods_serializer.data

    class Meta:
        model = GoodsCategory
        fields = '__all__'